package com.swyc.osschat;

import com.swyc.osschat.Common.Constant.Constant;
import com.swyc.osschat.Common.Exception.ServiceException;
import com.swyc.osschat.Common.Exception.SysErrorCode;
import com.swyc.osschat.Common.Util.System.SystemUtil;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.FileSystemResource;

import java.util.Objects;
import java.util.Properties;

@SpringBootApplication
@MapperScan("com.swyc.osschat")
public class OsschatApplication {

    public static void main(String[] args) {
        SpringApplication.run(OsschatApplication.class, args);
    }
    @Bean
    public static PropertySourcesPlaceholderConfigurer properties() {
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        /**主配置文件*/
        Properties mainYam = null;
        /**最终配置文件*/
        Properties all = new Properties();
        /**次配置文件*/
        Properties secendYam = new Properties();
        String secendStr = "";
        StringBuilder strb = new StringBuilder();
        strb.append(SystemUtil.isOsLinux()?SystemUtil.getLinxuHome():"C:/data/")
                .append("/chat/")
                .append(Constant.APPLICATION)
                .append(".yml");
        YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
        yaml.setResources(new FileSystemResource(strb.toString()));//File引入
        //yaml.setResources(new ClassPathResource("application-dev.yml"));//class引入
        mainYam = yaml.getObject();
        all.putAll(mainYam);
        if (!Objects.isNull(mainYam)){
            secendStr = String.valueOf(mainYam.get(Constant.EVN)).trim();
        }
        YamlPropertiesFactoryBean yam2 = new YamlPropertiesFactoryBean();
        StringBuilder secendStrb = new StringBuilder();
        try {
            secendStrb.append(SystemUtil.javaHomePath());
        } catch (Exception e) {
            throw new ServiceException(SysErrorCode.FAIL,"获取项目根目录错误！");
        }
        secendStrb.append("/application-").append(secendStr).append(".yml");
        yam2.setResources(new FileSystemResource(secendStrb.toString()));
        secendYam=yam2.getObject();
        all.putAll(secendYam);
        configurer.setProperties(all);
        return configurer;
    }

}
